package logic

import (
	"context"
	"fmt"
	"sz2/C/rpc/model/mysql"
	"sz2/C/rpc/model/redis"

	"sz2/C/rpc/good"
	"sz2/C/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *good.LoginRequest) (*good.LoginResponse, error) {
	// todo: add your logic here and delete this line
	redis.Rdb.Get(context.Background(), "smslogin"+in.Phone)
	g := mysql.User{}
	err := g.GetCreate(in.Phone)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if g.ID == 0 {
		g = mysql.User{
			Phone:    in.Phone,
			Password: in.Password,
		}
		err = g.Create()
		if err != nil {
			return nil, fmt.Errorf("注册失败")
		}
	}
	if in.Password != g.Password {
		return nil, fmt.Errorf("密码错误")
	}
	return &good.LoginResponse{Id: int64(g.ID)}, nil
}
